package com.jrx.anytxn.param.job.paph.step;

import com.jrx.anytxn.common.uitl.BeanUtils;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlFilePaymentLog;
import com.jrx.anytxn.param.job.paph.bean.PrepayFileBean;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author liuyu
 * @Description 解析文件, 并拼装成tl_file_payment_log的对象
 */
@Service
public class ReadPrepayFileProcessor implements ItemProcessor<PrepayFileBean, TlFilePaymentLog> {

	private static final Logger logger = LoggerFactory.getLogger(ReadPrepayFileProcessor.class);

	@Autowired
	private ISegmentService segmentService;
	@Autowired
	private IOrganizationTableService organizationTableService;

	@Override
	public TlFilePaymentLog process(PrepayFileBean item) throws Exception {
		TlFilePaymentLog log = new TlFilePaymentLog();

		PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
		log.setId(segmentService.getId(Constant.TL_FILE_PAYMENT_LOG));
		log.setTenantId(org.getTenantId());
		// 订单号
		if (StringUtils.isBlank(item.getLoanNo()) || StringUtils.isBlank(item.getTradeDate()) ||
				StringUtils.isBlank(item.getTradeSeqNo()) || StringUtils.isBlank(item.getTradeType()) ||
				null == item.getTradeAmt()) {
			Map<String, Object> map = BeanUtils.toMap(item);
			logger.error("必填字段存在空值:{}", map);
			throw new RuntimeException("必填字段存在空值:" + map);
		}
		log.setLoanId(item.getLoanNo());
		// 文件还款日期
		Date date = DateUtils.parseDate(item.getTradeDate(), "yyyyMMdd");
		log.setTradeDate(date);
		// 还款总金额
		log.setTradeAmt(item.getTradeAmt());
		// 扣款交易流水号
		log.setTradeSeqNo(item.getTradeSeqNo());
		// 提前还款类型
		log.setTradeFlag(item.getTradeType());
		// 扣款账户标识
		log.setAcctFlag(item.getAcctFlag());
		// 创建时间
		log.setCreateTime(new Date());
		return log;
	}
}
